// app.js
App({
  onLaunch() {
    // 检查用户登录状态
    this.checkLoginStatus()
  },

  // 检查登录状态
  checkLoginStatus() {
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      this.globalData.userInfo = userInfo
      this.globalData.isLoggedIn = true
    } else {
      this.globalData.isLoggedIn = false
    }
  },

  // 微信登录
  wxLogin() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          if (res.code) {
            // 获取用户信息
            wx.getUserProfile({
              desc: '用于完善用户资料',
              success: (profileRes) => {
                const userInfo = profileRes.userInfo
                userInfo.code = res.code
                
                // 保存用户信息到本地存储
                wx.setStorageSync('userInfo', userInfo)
                this.globalData.userInfo = userInfo
                this.globalData.isLoggedIn = true
                
                resolve(userInfo)
              },
              fail: (err) => {
                reject(err)
              }
            })
          } else {
            reject(new Error('登录失败'))
          }
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  },

  // 退出登录
  logout() {
    wx.removeStorageSync('userInfo')
    this.globalData.userInfo = null
    this.globalData.isLoggedIn = false
  },

  globalData: {
    userInfo: null,
    isLoggedIn: false
  }
})